#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define MYPORT "1999"
#define BUFSIZE 1024
#define IPSTRSIZE 1024

int Retlisten(char *MYIP)
{
    int sockFd;

    sockFd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockFd < 0)
    {
        perror("socket()");
        exit(1);
    }
        
    int val = 1;
    if (setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
    {
        perror("setsockopt()");
        exit(1);
    }

    struct sockaddr_in myAddr;
    myAddr.sin_family = AF_INET;
    myAddr.sin_port = htons(atoi(MYPORT));
    inet_pton(AF_INET, MYIP, &myAddr.sin_addr);

    if (bind(sockFd, (void *)&myAddr, sizeof(myAddr)) < 0)
    {
        perror("bind()");
        exit(1);
    }

    if (listen(sockFd, 10) < 0)
    {
        perror("listen()");
        exit(1);
    }

    return sockFd;
}

void job(int contfd)
{
    char buff[BUFSIZE] = {0};
    int ret;

    while (1)
    {
        ret = recv(contfd, buff, BUFSIZE, 0);
        if (ret > 0)
        {
            buff[ret] = '\0';
            puts(buff);
        }
        char *sendmsg = "I am recv\n";
        send(contfd, sendmsg, strlen(sendmsg), 0);
    }
}

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "Usage:\n");
        exit(1);
    }

    int contfd;
    int sockFd;
    struct sockaddr_in client;
    char ipStr[IPSTRSIZE] = {0};
    pid_t pid;

    socklen_t len = sizeof(client);
    sockFd = Retlisten(argv[1]);
    while (1)
    {
        contfd = accept(sockFd, (void *)&client, &len);
        if (contfd < 0)
        {
            perror("accept()");
            exit(1);
        }   

        pid = fork();
        if (pid < 0)
        {
            perror("fork()");
            exit(1);
        }
        if (pid == 0)
        {
            close(sockFd);

            inet_ntop(AF_INET, &client.sin_addr, ipStr, IPSTRSIZE);
            printf("Client :%s :%d\n", ipStr, ntohs(client.sin_port));
            job(contfd);
            close(contfd);
            exit(0);
        }
        close(contfd);
        
    }

    shutdown(sockFd, SHUT_RDWR);
}
